import pandas as pd  
import matplotlib.pyplot as plt  
import matplotlib.dates as mdates  
plt.rcParams['font.sans-serif'] = ['GB_HT_GBT2312'] 

def plot_direction_data(ax, data, direction_column, value_column, label_prefix, threshold, color_above, color_below):  
    legend_labels = []  # 用于存储图例的标签
    for direction in ['北', '东', '南', '西']:  
        direction_indices = data[direction_column] == direction  
        values = data[value_column][direction_indices]  
        times = data.loc[direction_indices, 'Time']  

        # 绘制线图  
        line, = ax.plot(times, values, label=f'{label_prefix} {direction}')  
        legend_labels.append(line)  # 将线对象添加到图例标签列表

        # 绘制散点图  
        colors = [color_above if val >= threshold else color_below for val in values]  
        ax.scatter(times, values, c=colors, marker='o')  

        # 添加标注
        for time, value in zip(times, values):
            ax.annotate(round(value,1), (time, value))

    # 设置图例
    ax.legend(handles=legend_labels, labels=['North (Color)', 'East (Color)', 'South (Color)', 'West (Color)'], loc='upper left', bbox_to_anchor=(0.01, 0.99), ncol=2)

# 读取数据  
data = pd.read_csv('averages.csv', header=None, names=['Time', 'Direction', 'Humidity', 'Temperature'], parse_dates=['Time'])  

# 设置图形大小  
plt.figure(figsize=(12, 8))  

# 创建湿度图  
ax1 = plt.subplot(2, 1, 1)  
plot_direction_data(ax1, data, 'Direction', 'Humidity', 'Humidity (%)', 45, 'g', 'r')  
ax1.set_xlabel('Time')  
ax1.set_ylabel('Humidity (%)')  
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  
ax1.xaxis.set_major_locator(mdates.MinuteLocator(interval=2))  
ax1.tick_params(axis='x', rotation=45)  
ax1.grid(True)  
ax1.set_title('Humidity Data')  

# 创建温度图  
ax2 = plt.subplot(2, 1, 2)  
plot_direction_data(ax2, data, 'Direction', 'Temperature', 'Temperature (°C)', 22, 'r', 'g')  
ax2.set_xlabel('Time')  
ax2.set_ylabel('Temperature (°C)')  
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  
ax2.xaxis.set_major_locator(mdates.MinuteLocator(interval=2))  
ax2.tick_params(axis='x', rotation=45)  
ax2.grid(True)  
ax2.set_title('Temperature Data')  

# 显示图形  
plt.tight_layout()  
plt.show()